package com.unipv14.androidgallery;

import listeners.MenuListener;
import listeners.SoftwareBackButtonListener;
import playlistData.PlaylistManager;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.ImageButton;
import fileManagers.FileListGetter;

public class MainActivity extends Activity{
	private FileListGetter getter;
	private PlaylistManager playlistManager;
	private static final int SMALL_SIZE_WIDTH = 400;
	private ListsRefresher listsRefresher;
	private MenuListener menuListener;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		try {
			if (getter == null) {
				getter = new FileListGetter();
			}
			if (savedInstanceState == null) {
				savedInstanceState = new Bundle();
				savedInstanceState
						.putString("directory", getter.getDirectory());
			} else {
				getter.setDirectory(savedInstanceState.getString("directory"));
			}
			super.onCreate(savedInstanceState);
			playlistManager = new PlaylistManager();
			onConfigurationChanged(getResources().getConfiguration());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		int fileListID;
		int playlistID;
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
				&& metrics.widthPixels < SMALL_SIZE_WIDTH) {
			setContentView(R.layout.small_portrait_main);
			fileListID = R.id.fileListP;
			playlistID = R.id.playlistP;
		} else {
			setContentView(R.layout.default_activity_main);
			fileListID = R.id.fileListL;
			playlistID = R.id.playlistL;
		}
		listsRefresher = new ListsRefresher(this, getter, fileListID,
				playlistID, playlistManager);
		listsRefresher.refreshList();
		menuListener=new MenuListener(this,playlistManager,listsRefresher);
		ImageButton backButton=(ImageButton)findViewById(R.id.backPlaylistButton);
		backButton.setOnClickListener(new SoftwareBackButtonListener(
				playlistManager,listsRefresher));
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putString("directory", getter.getDirectory());
		super.onSaveInstanceState(outState);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menuListener.createMenu(menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		menuListener.buttonPressed(item);
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onBackPressed() {
		if (getter.isExternalStorageDirectory()) {
			finish();
		} else {
			getter.goToParent();
			listsRefresher.refreshList();
		}
	}
}